<script>
import moment from "moment";

export default {
  name: "brandManagement",
  data() {  //data写成函数的作用：实现数据隔离，互不影响
    return {
      carList: [
        {
          id: '1',
          name: '奔驰',
          Ctime: new Date()
        },
        {
          id: '2',
          name: '宝马',
          Ctime: new Date()
        }
      ],
      carId: '',
      carName: '',
      keyword: '',
      delIndex:'',
      oldName:'',
      newName:'',
      modifyIndex:''
    }
  },
  methods: {
    // 添加按钮
    add() {
      // console.log('添加')
      // console.log(this.carId)
      // console.log(this.carName)


      // 两种方法判断id是否重复 find或者some
      // console.log(this.carList.find(item=>item.id===this.carId))   //判断id是否重复，重复的id会显示undefined
      // console.log(this.carList.some(item => item.id === this.carId))   //判断id是否重复，重复的id会显示true
      if (this.carList.find(item => item.id === this.carId)) {     //判断id是否重复，如果重复则弹框，不重复则push
        // if (this.carList.some(item => item.id === this.carId)) {
        alert('id重复')
      } else {
        this.carList.push({
          id: this.carId,
          name: this.carName,
          Ctime: new Date()
        })

        // 本地缓存，当点击添加按钮时，本地存储
        // localStorage.setItem('carList',JSON.stringify(this.carList))
        this.getLocal()

      }
      // console.log(this.carList)
      /*// 三目表达式的方法实现
      this.carList.some(item => item.id === this.carId)?alert('id重复'):this.carList.push({
        id: this.carId,
        name: this.carName,
        Ctime: new Date()
      })*/


      // 添加结束后要清空掉框里的内容
      this.carId = ''
      this.carName = ''

    },


    //   删除按钮
    /*// 当先搜索宝马时，点击删除按钮，会把奔驰那一行删掉，而不是把宝马那一行删掉
    del(i) {
      //   splice（要截取元素的index，length） 会改变原数组
      //   console.log(i)
      this.carList.splice(i, 1)    //截取之后的数组

      // console.log(this.carList.splice(i,1))  //打印的是要删除的
      // console.log(this.carList)   //打印的是剩下的显示的

    },*/
    // 当先搜索宝马时，点击删除按钮，把宝马那一行删掉，不会把奔驰那一行删掉(搜索不会再影响删除)
    del(item) {
      // 获取剩余元素的索引 indexOf
      console.log(this.carList.indexOf(item))   //item的索引
      // this.carList.splice(this.carList.indexOf(item), 1)

      this.delIndex=this.carList.indexOf(item)

    //
    },



    // 确认删除按钮
    confirmDel(){
      this.carList.splice(this.delIndex, 1)
      // this.carList.splice(this.carList.indexOf(item), 1)

      // localStorage.setItem('carList',JSON.stringify(this.carList))
      this.getLocal()

    },



    // 搜索
    search() {
      // console.log(this.keyword)
      // console.log(this.carList.filter(item=>item.name.includes(this.keyword)))
      // this.carList=this.carList.filter(item=>item.name.includes(this.keyword))   //当输入框不输入时，不能返回原数组
      // console.log(this.carList)


      // 用函数的返回值，当输入框不输入时，会返回原数组
      return this.carList.filter(item => item.name.includes(this.keyword))
    },


    // 修改按钮
    modify(item){
      // console.log(item.name)
      this.oldName=item.name
      this.modifyIndex=this.carList.indexOf(item)
      console.log(this.modifyIndex)
    },


    //   确认修改按钮
    confirmModify() {
      console.log(this.newName)
      this.carList[this.modifyIndex].name=this.newName
      this.newName=''
      this.getLocal()
      },


  //   封装缓存
    getLocal(){
      localStorage.setItem('carList',JSON.stringify(this.carList))
    }




  },
  filters:{
    filterTime(data,format){
      console.log(data,format)
      /*let Y =data.getFullYear().toString().padStart(2,0)
      let M=(data.getMonth()+1).toString().padStart(2,0)
      let D=data.getDate().toString().padStart(2,0)*/
      // console.log(data.getDay().toString().padStart(2,0))

      /*// 补0函数
      if(M<10){
        M='0'+M
      }*/
      /*// padStart（n，0）  不够n位，前面补0
      let str='5';
      console.log(str.padStart(2,0))
      console.log(str.padStart(3,'a'))
      console.log(str.padStart(10,'abcd'))*/


      // console.log(Y,M,D)
      // console.log(format.replace('YYYY',Y).replace('MM',M).replace('DD',D))


      // return `${Y}/${M}/${D}`

      // 也可以用Day.js
      console.log(moment(data).format(format),'moment')
      return moment(data).format(format)

      // return format.replace('YYYY',Y).replace('MM',M).replace('DD',D)
    }
  },

  created(){
    // console.log(localStorage.getItem('carList'))//数组
    // this.carList=localStorage.getItem('carList')//报错
    this.carList=JSON.parse(localStorage.getItem('carList'))||[]
  }
}

</script>

<template>
  <div>品牌管理
    <div class="card container">
      <!-- 头部-->
      <div class="card-header">添加品牌</div>
      <!-- 主体-->
      <div class="card-body">
        <form class="form-inline" action="">
          <label for="email" class="mr-sm-2">ID:</label>
          <input type="text" class="form-control mb-2 mr-sm-2" v-model="carId">
          <label for="pwd" class="mr-sm-2">Name:</label>
          <input type="text" class="form-control mb-2 mr-sm-2" v-model="carName">
          <button type="button" class="btn btn-primary mb-2" @click="add">添加</button>
          <label for="pwd" class="mr-sm-2">搜索关键字:</label>
          <input type="text" class="form-control mb-2 mr-sm-2" @change="search" v-model="keyword">
          <!--          //@change="search"当输入框失去焦点时输出一次-->
          <!--          <input type="text" class="form-control mb-2 mr-sm-2" @input="search" v-model="keyword">    //@input="search"键盘每按下一次，就输出一次（一边输入一边输出）-->
        </form>
      </div>
      <!-- 底部-->
      <div class="card-footer">
        <table class="table table-striped">
          <thead>
          <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Ctime</th>
            <th>Operation</th>
          </tr>
          </thead>
          <tbody>
          <tr v-for="(item) in search()" :key="item.id">
            <!--          <tr v-for="(item,index) in search()" :key="item.id">-->
            <!--            <tr v-for="(item,index) in carList" :key="item.id">-->

            <td>{{ item.id }}</td>
            <td>{{ item.name }}</td>
            <td>{{ item.Ctime |filterTime('YYYY/MM/DD hh:mm:ss')}}
            ----{{ item.Ctime |filterTime('YYYY-MM-DD hh:mm:ss')}}
            </td>
            <td>
              <!--              <button type="button" class="btn btn-danger" @click="del(index)">删除</button>-->
              <button type="button" class="btn btn-danger" data-toggle="modal" data-target="#myModal1"
                      style="margin-right:20px" @click="del(item)">删除
              </button>
              <button type="button" class="btn btn-success" data-toggle="modal" data-target="#myModal2" @click="modify(item)">修改</button>







            </td>
          </tr>
          <!--        <tr>-->
          <!--          <td>1</td>-->
          <!--          <td>奔驰</td>-->
          <!--          <td>2024</td>-->
          <!--          <td><button type="button" class="btn btn-danger">删除</button></td>-->
          <!--        </tr>-->
          <!--        <tr>-->
          <!--          <td>2</td>-->
          <!--          <td>宝马</td>-->
          <!--          <td>2023</td>-->
          <!--          <td><button type="button" class="btn btn-danger">删除</button></td>-->
          <!--        </tr>-->
          </tbody>
        </table>
      </div>
    </div>


    <!-- 删除的模态框 -->
    <div class="modal fade" id="myModal1">
      <div class="modal-dialog modal-sm">
        <div class="modal-content">

          <!-- 模态框头部 -->
          <div class="modal-header">
            <h4 class="modal-title">删除？</h4>
            <button type="button" class="close" data-dismiss="modal">&times;</button>
          </div>

          <!-- 模态框主体 -->
          <div class="modal-body">
            确定删除吗？
          </div>

          <!-- 模态框底部 -->
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal" @click="confirmDel">确定删除</button>
            <button type="button" class="btn btn-secondary" data-dismiss="modal" >关闭</button>

          </div>

        </div>
      </div>
    </div>





    <!--   修改模态框 -->
    <div class="modal fade" id="myModal2">
      <div class="modal-dialog">
        <div class="modal-content">

          <!-- 模态框头部 -->
          <div class="modal-header">
            <h4 class="modal-title">修改</h4>
            <button type="button" class="close" data-dismiss="modal">&times;</button>
          </div>

          <!-- 模态框主体 -->
          <div class="modal-body">
            <p>原来的名字：{{oldName}}</p>
            <p>新名字：<input type="text" v-model="newName"></p>
          </div>

          <!-- 模态框底部 -->
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal" @click="confirmModify">确认修改</button>
            <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
          </div>
        </div>
      </div>
    </div>






  </div>
</template>

<style scoped lang="less">

</style>